import Axios from 'axios'
// import Store from 'store/index'
import { Toast } from 'vant'
import router from '../router'
Axios.defaults.timeout = 50000 // 请求超时时间
// Axios.defaults.baseURL = process.env.VUE_APP_BASE_API

// post请求头的设置
// Axios.defaults.headers.post['Content-Type'] =
//     'application/x-www-form-urlencoded;charset=UTF-8'

// axios respone拦截器
Axios.interceptors.response.use(
  response => {
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误 结合自身业务和后台返回的接口状态约定写respone拦截器

    if (response.status === 200) {
      return Promise.resolve(response)
    } else if (response.status === -1) {
      Toast({
        message: response.data.message,
        position: 'middle',
        duration: 2000
      });
      this.$goRoute('login')
    } else {
      Toast({
        message: response.data.message,
        position: 'middle',
        duration: 2000
      });
      this.$goRoute('login')
      return Promise.reject(response)
    }
  },
  error => {
    console.log(error)
    const responseCode = error.response.status
    switch (responseCode) {
      // 401：未登录
      case 401:
        this.$goRoute('login')
        break
        // 404请求不存在
      case 404:
        Toast({
          message: '网络请求不存在',
          position: 'middle',
          duration: 2000
        });
        break
      default:
        Toast({
          message: error.response.data.message,
          position: 'middle',
          duration: 2000
        });
    }

    return Promise.reject(error.response)
  }
)
/**
 * 封装get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
function get (url, headers) {
  // console.log(url, 'url');
  console.log(666);
  let urlArray = url.split('/')
  // console.log(urlArray, 'urlArray');
  let loginMessage = JSON.parse(localStorage.getItem('loginMessage'))
  console.log(loginMessage, 'loginMessage');
  if (urlArray[urlArray.length - 1] !== 'login' && urlArray[urlArray.length - 1] !== 'getVSession' && loginMessage && loginMessage.sessionKey !== undefined) {
    Axios.defaults.headers.get[loginMessage.sessionKey] = loginMessage.sessionId
  } else if (!loginMessage || loginMessage.sessionKey === undefined) {
    Axios.defaults.headers.get['SHARE_JSESSIONID'] = ''
  }
  // console.log('判断完成 请求接口');
  return new Promise((resolve, reject) => {
    // Toast.loading({
    //   message: '正在加载中...',
    //   forbidClick: true
    // });
    Axios.get(url, headers).then(res => {
      if (res.data.status === -1) {
        router.push({ name: 'login' })
      }
      resolve(res)
    }).catch(err => {
      reject(err)
    })
      .finally(res => {
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * 通过node的qs模块来序列化我们的参数  没有序列化操作，后台是拿不到你提交的数据
 */
function post (url, params, headers) {
  let urlArray = url.split('/')
  let loginMessage = JSON.parse(localStorage.getItem('loginMessage'))
  if (loginMessage == null) {
    Axios.defaults.headers['SHARE_JSESSIONID'] = ''
  } else {
    if (urlArray[urlArray.length - 1] !== 'login') {
      Axios.defaults.headers[loginMessage.sessionKey] = loginMessage.sessionId
    } else {
      Axios.defaults.headers[loginMessage.sessionKey] = ''
    }
  }
  return new Promise((resolve, reject) => {
    // Toast.loading({
    //   message: '正在加载中...',
    //   forbidClick: true
    // });
    Axios.post(url, params, headers)
      .then(res => {
        if (res.data.status === -1) {
          if (localStorage.getItem('saveRouter') == null) {
            localStorage.setItem('preRoute', router.currentRoute.fullPath)
            localStorage.setItem('saveRouter', 'hadSave')
          }
          router.push({ name: 'login' })
        }
        resolve(res)
      })
      .catch(err => {
        console.log('post:::::reject', err)
        reject(err)
      })
      .finally(res => {
        /*   setTimeout(() => {
          Toast.clear()
        }, 1000) */
      })
  })
}

export { get, post }
